<script setup>
import { ref, onMounted } from 'vue'
import { sessionApi, modTreeApi, pageBtnApi, saveBtnApi, delBtnsApi, oneBtnApi, sortBtnApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pagination/UbtPager.vue'
import UbtTreeSel from '@/components/cascader/UbtTreeSel.vue'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1001010201') !== -1,
      delAuth: userBtnCode.indexOf('1001010202') !== -1,
      edtAuth: userBtnCode.indexOf('1001010203') !== -1
    }
    selMods()
    list(0, 1)
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const schObj = {
  schName: '',
  modId: '',
  modName: '',
  modCode: '',
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const btnList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageBtnApi(schRef.value)
  if(res.code === 200 && res.data) {
    hasData.value = true
    total.value = res.data.total
    btnList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    schName: '',
    modId: '',
    modName: '',
    modCode: '',
    offset: 0,
    limit: 20
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    btnList.value.forEach(item => {
      idList.value.push(item.roleId)
      checkList.value.push(true)
    })
  } else {
    btnList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, roleId) => {
  if(!checkList.value[idx]) {
    idList.value.push(roleId)
  } else {
    const index = idList.value.findIndex(id => {
      if (id === roleId) {
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const btnObj = {
  btnId: '',
  btnName: '',
  btnCode: '',
  modId: '',
  sort: 0
}
const btnForm = ref(btnObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (btnId) => {
  const res = await oneBtnApi({ btnId })
  if(res.code === 200) {
    showModal.value = true
    btnForm.value = res.data
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let btnName = btnForm.value.btnName
  let btnCode = btnForm.value.btnCode
  let modId = btnForm.value.modId
  let sort = parseInt(btnForm.value.sort)
  if(btnName === '' || btnName.length > 50) {
    Msg({ kind: 'warn', txt: '按钮名称不能为空，且长度不超过10个字符！' })
    return
  } else if(btnCode === '' || btnCode.length > 30) {
    Msg({ kind: 'warn', txt: '按钮编码不能为空，且长度为10位的数字编码！' })
    return
  } else if(modId === '' || modId.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择所属模块！' })
    return
  } else if(sort === 0) {
    Msg({ kind: 'warn', txt: '请输入按钮排序，必须为数字！' })
    return
  }
  const res = await saveBtnApi(btnForm.value)
  if(res.code === 200) {
    closeModal()
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，按钮信息保存成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  btnForm.value = {
    btnId: '',
    btnName: '',
    btnCode: '',
    modId: '',
    sort: 0
  }
}

// process 删除按钮
const process = async() => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要删除选中的按钮吗？').then(() => {
    delBtns()
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// delBtns 删除按钮实现，分离出来防止调用时异步报错
const delBtns = async () => {
  let btnIds = idList.value.join(',')
  const res = await delBtnsApi({ btnIds })
  if(res.code === 200) {
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，按钮信息删除成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// 所有模块数组
const modList = ref([])
// selMods 获取模块及按钮列表
const selMods = async () => {
  const res = await modTreeApi()
  if(res.code === 200) {
    modList.value = res.data
  }
}

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.modId = item.selId
      schRef.value.modName = item.selName
      schRef.value.modCode = item.selCode
      break
    case 2:
      sort(item.selId, item.selCode)
      btnForm.value.modId = item.selId
      btnForm.value.modName = item.selName
      btnForm.value.modCode = item.selCode
      break
  }
}

// sort 按钮排序
const sort = async (modId, modCode) => {
  const res = await sortBtnApi({ modId })
  if(res.code === 200) {
    btnForm.value.sort = res.data
    btnForm.value.btnCode = modCode + '0' + res.data
  }
}
</script>

<template>
  <div class="a">
    <!-- 头部按钮 -->
    <div class="b">
      <div v-if="procAuth.addAuth" class="btn-p" title="新增" @click="add()"><i class="iconfont doc_text"></i> 新增</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="process()"><i class="iconfont trash"></i> 删除</div>
      <div class="btn-r" title="筛选" @click="search()"><i class="iconfont search"></i></div>
      <div class="btn-r" title="刷新" @click="list(0, 1)"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部数据 -->
    <div class="c" v-if="schShow">
      <div class="d"><input type="text" v-model="schRef.schName" placeholder="请输入名称或编码的关键字" class="e" /></div>
      <div class="d"><ubt-tree-sel :kind="1" :tree-list="modList" :inboxed="true" :curName="schRef.modName!=='' ? schRef.modName+'['+schRef.modCode+']' : ''" pre-name="所属模块" @setValue="setValue" /></div>
      <div class="btn-p" @click="list(0, 1)"><i class="iconfont search"></i> 筛选</div>
      <div class="btn-d" @click="clrSch()"><i class="iconfont arrowshape_turn_up_left"></i> 重置</div>
    </div>
    <div class="f" v-if="hasData">
      <table>
        <tr>
          <th style="width: 10%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 25%;">模块</th>
          <th style="width: 15%;">名称</th>
          <th style="width: 20%;">编码</th>
          <th style="width: 15%;">排序</th>
          <th style="width: 15%;">操作</th>
        </tr>
        <tr v-for="(curBtn, index) in btnList" :key="curBtn.btnId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curRole.btnId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td class="txt-center">{{curBtn.modName}}[{{curBtn.modCode}}]</td>
          <td class="txt-center">{{curBtn.btnName}}</td>
          <td class="txt-center">{{curBtn.btnCode}}</td>
          <td class="txt-center">{{curBtn.sort}}</td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-blue" title="修改" @click="update(curBtn.btnId)"><i class="iconfont square_pencil"></i> 修 改</span>
          </td>
        </tr>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_plaintext fs20"></i> 保存按钮信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>按钮名称</div>
                <div><input type="text" v-model="btnForm.btnName" maxlength="50" placeholder="请输入按钮名称" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>所属模块</div>
                <ubt-tree-sel :tree-list="modList" :kind="2" :inboxed="false" :curName="btnForm.modName ? btnForm.modName+'['+btnForm.modCode+']' : ''" pre-name="所属模块" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>按钮编码</div>
                <div><input type="text" v-model="btnForm.btnCode" maxlength="30" placeholder="请输入按钮编码" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>按钮排序</div>
                <div><input type="text" v-model="btnForm.sort" maxlength="30" placeholder="请输入按钮排序" class="txt" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="save()"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal()"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {margin: 0 10px 10px 10px; border: 1px solid #CCC; display: flex; display: -webkit-flex; padding: 15px;}
.d {flex-grow: 1;}
.e {width: 230px; padding: 8px;}
.f {background-color: #FFF;}
</style>
